<template>
  <div class="content-container">
    <!-- 搜索栏 -->
    <div ref="adminContentSearch" class="content-search-wrap">
      <el-form 
      	class="content-search"
      	inline
      	size="mini"
      >
        <el-form-item label="账号">
          <el-input v-model="userId.account" placeholder="请输入账号"></el-input>
        </el-form-item>

        <el-form-item>
    		<el-button size="mini" type="primary">搜索</el-button>
    		<el-button size="mini" type="danger">清空</el-button>
  		</el-form-item>
      </el-form>
    </div>
    <!-- 工具栏 -->
    <div ref="adminContentTools" class="content-tools-wrap hidden">
      	<div class="tools-left f-l">
      		
      		<el-button-group>
			      <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleAdd">新增</el-button>
			    </el-button-group>

      	</div>
      	<div class="tools-right f-r">
      		<el-tooltip effect="dark" content="刷新" placement="top">
			       <el-button size="mini" type="primary" icon="el-icon-refresh" circle @click="refresh"></el-button>
          </el-tooltip>   
      	</div>
    </div>
    <!-- 内容栏--表格 -->
    <div class="content-table-wrap" v-loading="loading" loading-type="chrome-circle-turn" :style="{height:ResultHeight+'px'}">
    	<el-table
        v-if="data"
        border
    		size="mini"
    		:data="data"
        :height.sync="tableHeight"
    		style="width: 100%"
    	>
    		<el-table-column
		      type="selection"
		      width="55">
		    </el-table-column>

    		<el-table-column
    			fixed
		      	type="index"
		      	:index="tableIndex">
		    </el-table-column>

    		<el-table-column
		      fixed
		      prop="account"
		      label="账号"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="name"
		      label="姓名"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="deptName"
		      label="部门"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="positionName"
		      label="职位"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="phone"
		      label="电话"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="email"
		      label="电子邮箱"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="birthday"
		      label="用户生日"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="sex"
		      label="用户性别"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="status"
		      label="账号状态"
		      width="150">
		      <template slot-scope="scope">
		      	<el-switch
				      v-model="scope.row.$status"
				      active-color="#13ce66"
				      inactive-color="#ff4949"
              @change="statusChange(scope.row)"
            >
				    </el-switch>
		      </template>
		    </el-table-column>

		    <el-table-column
		      prop="createTime"
		      label="创建时间"
		      width="150">
		    </el-table-column>

		    <el-table-column
		    	fixed="right"
		      	label="操作"
		      	width="250"
		    >

		      <template slot-scope="scope">
		      	<el-button
		      		size="mini"
		      		type="primary"
		      		@click="handleEdit(scope.$index, scope.row)"
		      	>编辑</el-button>

		      	<el-button
		      		size="mini"
		      		type="primary"
		      		@click="handleDel(scope.$index, scope.row)"
		      	>删除</el-button>

		      	<el-button
		      		size="mini"
		      		type="primary"
		      		@click="handleRoles(scope.$index, scope.row)"
		      	>分配角色</el-button>

		      </template>

		    </el-table-column>

    	</el-table>  

      <!-- 分页 -->
      <div ref="adminContentPagination" class="content-pagination-wrap">
        <el-pagination
          background
          :current-page="page.currentPage"
          :page-sizes="pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>

    


    <!-- 修改dialog -->
    <mgr-edit-dialog
    	:visible="editDialogVisible"
    	:form.sync='editForm'
    	:type="editType"
    	@cancel="editDialogCancel"
    	@confirm="editDialogConfirm"
    ></mgr-edit-dialog>

    <!-- 分配角色dialog -->
    <el-dialog title="分配角色"
               :visible.sync="rolesDialog"
               width="40%">
      <el-scrollbar style="height:400px">
        <el-tree :data="rolesTree"
                 show-checkbox
                 node-key="id"
                 default-expand-all
                 @check="rolesChange"
                 :default-checked-keys="rolesKeys"
                 :props="{label:'name',value:'id'}">
        </el-tree>
      </el-scrollbar>
      <span slot="footer">
        <el-button type="primary"
                   size="small"
                   @click="handleSetRoles">确 定</el-button>
      </span>
    </el-dialog>



  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import {
  getList,
  getUser,
  remove,
  update,
  add,
  setRoles,
  changeStatus,
  resetPassword
} from "@/api/admin/mgr";
import { getRolesTree } from "@/api/admin/roles";
import MgrEditDialog from '@/components/Dialog/mgrEditDialog'

import adminMixins from "@/mixins/admin"
export default {
  name: 'mgr',
  mixins:[adminMixins],
  components:{
  	MgrEditDialog
  },
  computed: {
    ...mapGetters([
      'name',
      'permission',
      'userInfo',
      'mainContentHeight'
    ])
  },
  data(){
  	return{
  		//1新增，2修改
  		editType:1,
  		from:{},
  		//修改模态框的显示隐藏
  		editDialogVisible:false,
  		//分配角色模态框
  		rolesDialog:false,
  		rolesTree: [],
  		rolesKeys: [],
  		userId:{
  			account:''
  		},
      loading:false,
  		data:null,
  		page: {
        	pageSize: 10,
        	currentPage: 1,
        	total: 0
      	},
      	pageSizes:[10,20,30,40,50,100],
      	editForm:{}
  	}
  },
  mounted(){
    //设置dom尺寸
    this.setSize();
  	this.loadData(this.page);
  },
  methods:{
  	//请求table数据
  	loadData(page, params = {}){
  		  this.loading = true;
      	getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {

      		console.log("---views/admin/mgr--loadData----------")
      		console.log(res)
        	this.loading = false;
        	const data = res.data;
        	this.page.total = data.count;
        	this.data = this.convertData(data.data);
        	
      	});
      	getRolesTree(this.userInfo.id).then(res => {
        	this.rolesTree = res.data;
      	});
  	},
    //转换数据内容
    convertData(data){
      if(!data.length) return data;
      for(let i=0;i<data.length;i++){
        if(data[i].status === 'ENABLE'){
          data[i]['$status'] = true;
        }else{
          data[i]['$status'] = false;
        }
      }
      return data;
    },
    //切换状态
    statusChange(row){
      if (row.status === 'ENABLE') {
        changeStatus(row.userId, 'freeze');
      } else {
        changeStatus(row.userId, 'unfreeze');
      }
    },
  	//表格序号
  	tableIndex(index){
  		return index+1
  	},
  	//新增用户
  	handleAdd(){
  		this.editForm = null;
		  this.editType = 1;
		  //模态框显示
		  this.editDialogVisible = true;
  	},
    //刷新当前页
    refresh(){
      this.loadData(this.page)
    },
  	//点击操作的编辑
  	handleEdit(index,row){
  		console.log("-----views/admin/mgr--handleEdit------------")
  		console.log("index:"+index)
  		console.log(row)
  		
  		//获取当前点击用户数据
  		getUser(row.userId).then((res)=>{
  			console.log("-----views/admin/mgr--handleEdit--getUser----------")
  			console.log(res)
  			var info = res.data.data;

  			//转换职位为数组
        if(info.positionIds === ""){
          info.positionIds = [];
        }else{
          info.positionIds = info.positionIds.split(',');
        }
        //转换status
        if(info.status === 'ENABLE'){
          info["$status"] = true
        }else{
          info["$status"] = false
        }
  			
  			this.editForm = info;
  			this.editType = 2;

  			//模态框显示
  			this.editDialogVisible = true;
  		})
  	},
  	//点击操作的删除
  	handleDel(index,row){

  		this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          	confirmButtonText: '确定',
          	cancelButtonText: '取消',
          	type: 'warning'
        }).then(()=>{
        	return remove(row.userId);
        }).then((res) => {

        	this.loadData(this.page)
          	this.$message({
            	type: 'success',
            	message: '删除成功!'
          	});
        }).catch(() => {
          	this.$message({
            	type: 'info',
            	message: '已取消删除'
          	});          
        });
  	},
  	//分配角色
  	handleRoles(index,row){
  		this.form = row;
      	this.form.roleId = this.form.roleId || '';
      	this.rolesKeys = row.roleId.split(',')
      	this.rolesDialog = true;
  	},
  	rolesChange (data, checked) {
      this.form.roleId = checked.checkedKeys.join(',')
    },
    handleSetRoles () {
      setRoles(this.form.userId, this.form.roleId).then(() => {
        this.$message.success('设置成功');
        this.rolesDialog = false;
        this.loadData(this.page);
        this.form = {}
      })
    },
  	editDialogCancel(){
  		this.editDialogVisible = false;
  		this.editForm = null;
  	},
  	//新增，修改用户确认
  	editDialogConfirm(form){
  		if(form.type == 1){

  			console.log("--------form.data-----------")
  			console.log(form.data)

  			add(form.data).then((res)=>{

  				this.editDialogVisible = false;
  				this.loadData(this.page)
	          	this.$message({
	            	type: 'success',
	            	message: '添加成功!'
	          	});
  			})

  		}else if(form.type == 2){
  			update(form.data).then((res)=>{

  				this.editDialogVisible = false;
  				this.loadData(this.page)
	          	this.$message({
	            	type: 'success',
	            	message: '修改成功!'
	          	});
  			})
  		}	
  	}
  }
}
</script>

<style lang="scss" scoped>
.content {
  &-container {

  }
  /***搜索栏***/
  &-search-wrap{
    padding: 15px;
    border-bottom: 1px solid #E8EBEE;
  }
  /***工具栏***/
  &-tools-wrap{
    padding: 15px;
  }
  /***内容栏***/
  &-table-wrap{
    position: relative;
    padding: 15px;
  }
  /***分页***/
  &-pagination-wrap{
  	padding-top: 15px;
    text-align: right;
  }
}
</style>
